package avicit.cbb.elefileupdown.service.impl;

import avicit.cbb.elefileupdown.service.FileUploadIntfsService;
import avicit.cbb.techclass.bigsave.action.MongoDBManager;
import avicit.cbb.techclass.dxcc.S3Service;
import avicit.cbb.techclass.elefileconvert.service.impl.ConvertDocService;
import avicit.cbb.techclass.elefileconvert.service.impl.JProperties;
import avicit.cbb.techclass.elefileupdown.domain.CbbDocRelation;
import avicit.cbb.techclass.elefileupdown.service.FileUploadEvent;
import avicit.cbb.techclass.elefileupdown.service.FileUploadService;
import avicit.cbb.techclass.tabledefine.commtablemanager.action.CommTableSysFieldLoader;
import avicit.im.lantop.common.elefileupdown.elefileupdown.action.SwfUploadServlet;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.FileUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.core.dao.hibernate.CommonHibernateDao2;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.properties.PlatformConstant.OpType;
import avicit.platform6.core.spring.SpringFactory;
import avicit.platform6.fastdfs.utils.FastDfsUtil;
import avicit.platform6.modules.system.sysfileupload.domain.SysFileUpload;
import avicit.platform6.modules.system.sysfileupload.service.SysFileUploadService;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import com.amazonaws.services.s3.AmazonS3;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import org.apache.commons.io.IOUtils;
import org.hibernate.LobHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 金航数码科技有限责任公司
 * </p>
 * <p>
 * 作者：钟一华
 * </p>
 * <p>
 * 邮箱：feifan1985@163.com
 * </p>
 * <p>
 * 创建时间： 2015-6-10 下午6:17:29
 * </p>
 * <p>
 * 类说明：附件上传接口实现类
 * </p>
 * <p>
 * 修改记录：
 * </p>
 */
@Service
public class FileUploadIntfsServiceImpl implements FileUploadIntfsService {

	@Autowired(required = false)
	private CommonHibernateDao2 hibernateDao;
	@Autowired(required = false)
	private JdbcAvicit jdbcAvicit;
	@Autowired(required = true)
	private MongoDBManager mongoDBManager;
	@Autowired(required = true)
	private ConvertDocService docService;

	@Autowired(required = true)
	private CommTableSysFieldLoader commTableSysFieldLoader;

	private File uploadDir = null;
	private SysFileUploadService sysFileUploadService = (SysFileUploadService) SpringFactory.getBean(SysFileUploadService.class);
	private FileUploadService swfUploadService = (FileUploadService) SpringFactory.getBean("fileUploadService");
	private FileUploadEvent swfUploadEvent = swfUploadService.getAfterEvent();

	String bucketName = avicit.cbb.techclass.dxcc.JProperties.getFileProperties("bucketName");
	String folderName = avicit.cbb.techclass.dxcc.JProperties.getFileProperties("folderName");

	public S3Service getS3Service() {
		return S3Service.getInstance();
	}

	public AmazonS3 getS3() throws Exception {
		return getS3Service().getS3Instance();
	}

	/**
	 * 保存docrelation和sysmarker数据方法
	 * @param relationParam
	 * @param markerParam
	 * @throws Exception void
	 * @throws
	 */
	public void saveDocRelationSysMarkerData(Map<String, Object> relationParam, Map<String, Object> markerParam) throws Exception {
		String orgId = (String) relationParam.get("orgId");
		String deptId = (String) relationParam.get("deptId");
		String sysId = (String) relationParam.get("sysId");
		try {
			this.insertDocRelationDataByIntfs(orgId, deptId, sysId, relationParam);
			this.saveMarker(markerParam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加全文文件关系表数据
	 *
	 * @author 钟一华
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param param
	 *            参数param :[key:ARCHIVE_TABLE_ID value:表id type:string]
	 *            :[key:RECORD_ID value:记录id type:string] :[key:ATTACHMENT_ID
	 *            value:附件id type:string] :[key:ATTACHMENT_CATEGORY value:全文类别
	 *            type:string] :[key:ATTACHMENT_COVER_TYPE value:封面类型
	 *            type:string] :[key:DOC_DATASOURCE value:数据源 type:string]
	 *            :[key:DOC_SER_ID value:电子文件服务器id type:string]
	 *            :[key:DOC_SER_NAME value:电子文件服务器名称 type:string]
	 *            :[key:DOC_SER_PATH value:存放相对路径 type:string]
	 *            :[key:DOC_REL_VERSION value:全文版本 type:string] :[key:DOC_TRUE
	 *            value:真实性 type:string] :[key:DOC_INTEGRITY value:完整性
	 *            type:string] :[key:DOC_VALID value:有效性 type:string]
	 *            :[key:DOC_FINGER_CODE value:指纹编码 type:string] :[key:REMARK
	 *            value:备注 type:string]
	 * @throws Exception
	 *             void
	 * @throws
	 */
	public String insertDocRelationDataByIntfs(String orgId, String deptId, String sysId, Map<String, Object> param) throws Exception {
		CbbDocRelation cdr = new CbbDocRelation();
		String id = ComUtil.getId();
		try {
			// 关系表id
			cdr.setId(id);
			// 表ID
			cdr.setArchiveTableId(param.get("ARCHIVE_TABLE_ID") == null ? "" : (String) param.get("ARCHIVE_TABLE_ID"));
			// 记录id
			cdr.setRecordId(param.get("RECORD_ID") == null ? "" : (String) param.get("RECORD_ID"));
			// 全文记录id
			cdr.setAttachmentId(param.get("ATTACHMENT_ID") == null ? "" : (String) param.get("ATTACHMENT_ID"));
			// 全文类别
			cdr.setAttachmentCategory(param.get("ATTACHMENT_CATEGORY") == null ? "" : (String) param.get("ATTACHMENT_CATEGORY"));
			// 封面类型
			cdr.setAttachmentCoverType(param.get("ATTACHMENT_COVER_TYPE") == null ? "" : (String) param.get("ATTACHMENT_COVER_TYPE"));
			// 数据源
			cdr.setDocDatasource(param.get("DOC_DATASOURCE") == null ? "" : (String) param.get("DOC_DATASOURCE"));
			// 电子文件服务器id
			cdr.setDocSerId(param.get("DOC_SER_ID") == null ? "" : (String) param.get("DOC_SER_ID"));
			// 电子文件服务器名称
			cdr.setDocSerName(param.get("DOC_SER_NAME") == null ? "" : (String) param.get("DOC_SER_NAME"));
			// 存放相对路径
			cdr.setDocSerPath(param.get("DOC_SER_PATH") == null ? "" : (String) param.get("DOC_SER_PATH"));
			// 全文版本
			cdr.setDocRelVersion(param.get("DOC_REL_VERSION") == null ? "" : (String) param.get("DOC_REL_VERSION"));
			// 真实性
			cdr.setDocTrue("1");
			// 完整性
			cdr.setDocIntegrity("1");
			// 有效性
			cdr.setDocValid("1");
			// 指纹编码
			cdr.setDocFingerCode(param.get("DOC_FINGER_CODE") == null ? "" : (String) param.get("DOC_FINGER_CODE"));
			// 备注
			cdr.setRemark(param.get("REMARK") == null ? "" : (String) param.get("REMARK"));
			// 是否删除标识
			cdr.setIfDelete("N");
			// 全文描述
			cdr.setAllDescribe(param.get("ALL_DESCRIBE") == null ? "" : (String) param.get("ALL_DESCRIBE"));
			// 全文密级
			cdr.setSecretLevel(param.get("SECRET_LEVEL") == null ? "" : (String) param.get("SECRET_LEVEL"));
			// 组织id
			cdr.setOrgId(orgId);
			// 部门id
			cdr.setDeptId(deptId);
			// 系统标识id
			cdr.setSysId(sysId);
			// 上传类型
			cdr.setAttribute01(param.get("UPLOAD_TYPE") == null ? "" : (String) param.get("UPLOAD_TYPE"));
			// 附件OCR转换状态
			cdr.setAttribute02("0");
			if (param.containsKey("ATTRIBUTE_03") && null != param.get("ATTRIBUTE_03") && !"".equals(param.get("ATTRIBUTE_03")) && !"null".equals(param.get("ATTRIBUTE_03"))) {
				cdr.setAttribute03((String) param.get("ATTRIBUTE_03"));
			}
			// 稿本类型
			if (param.containsKey("ATTRIBUTE_04") && null != param.get("ATTRIBUTE_04") && !"".equals(param.get("ATTRIBUTE_04")) && !"null".equals(param.get("ATTRIBUTE_04"))) {
				cdr.setAttribute04((String) param.get("ATTRIBUTE_04"));
			}
			// 是否扫描件
			if (param.containsKey("ATTRIBUTE_05") && null != param.get("ATTRIBUTE_05") && !"".equals(param.get("ATTRIBUTE_05")) && !"null".equals(param.get("ATTRIBUTE_05"))) {
				cdr.setAttribute05((String) param.get("ATTRIBUTE_05"));
			}
			// 附件排序号
			if (param.containsKey("ATTRIBUTE_11") && null != param.get("ATTRIBUTE_11") && !"".equals(param.get("ATTRIBUTE_11")) && !"null".equals(param.get("ATTRIBUTE_11"))) {
				cdr.setAttribute11(BigDecimal.valueOf(Long.parseLong(param.get("ATTRIBUTE_11").toString())));
			}
			PojoUtil.setSysProperties(cdr, OpType.insert);
			this.hibernateDao.save(cdr);
			// SysLogUtil.log(cdr, null, OpType.insert, OpResult.success);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return id;
	}

	/**
	 * 更新全文文件关系表数据
	 *
	 * @author 钟一华
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param param
	 *            参数param :[key:ID value:id type:string] :[key:ARCHIVE_TABLE_ID
	 *            value:表id type:string] :[key:RECORD_ID value:记录id type:string]
	 *            :[key:ATTACHMENT_ID value:附件id type:string]
	 *            :[key:ATTACHMENT_CATEGORY value:全文类别 type:string]
	 *            :[key:ATTACHMENT_COVER_TYPE value:封面类型 type:string]
	 *            :[key:DOC_DATASOURCE value:数据源 type:string] :[key:DOC_SER_ID
	 *            value:电子文件服务器id type:string] :[key:DOC_SER_NAME
	 *            value:电子文件服务器名称 type:string] :[key:DOC_SER_PATH value:存放相对路径
	 *            type:string] :[key:DOC_REL_VERSION value:全文版本 type:string]
	 *            :[key:DOC_TRUE value:真实性 type:string] :[key:DOC_INTEGRITY
	 *            value:完整性 type:string] :[key:DOC_VALID value:有效性 type:string]
	 *            :[key:DOC_FINGER_CODE value:指纹编码 type:string] :[key:REMARK
	 *            value:备注 type:string]
	 * @throws Exception
	 *             void
	 * @throws
	 */
	public void updateDocRelationDataByIntfs(String orgId, String deptId, String sysId, Map<String, Object> param) throws Exception {
		String recordId = (String) param.get("RECORD_ID");
		String attachId = (String) param.get("ATTACHMENT_ID");
		String sql = "SELECT * FROM CBB_DOC_RELATION WHERE RECORD_ID = '" + recordId + "' AND ATTACHMENT_ID = '" + attachId + "'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		String id = "";
		if (list.size() > 0) {
			Map<String, Object> m = list.get(0);
			id = (String) m.get("ID");
		}
		if (null != id) {
			CbbDocRelation oldBean = this.hibernateDao.get(CbbDocRelation.class, id);
			this.hibernateDao.evict(oldBean);
			CbbDocRelation newBean = new CbbDocRelation();
			PojoUtil.copyProperties(newBean, oldBean, true);
			try {
				// 表ID
				newBean.setArchiveTableId((String) param.get("ARCHIVE_TABLE_ID"));
				// 记录id
				newBean.setRecordId((String) param.get("RECORD_ID"));
				// 全文记录id
				newBean.setAttachmentId((String) param.get("ATTACHMENT_ID"));
				// 全文类别
				if (null != param.get("ATTACHMENT_CATEGORY") && !"".equals(param.get("ATTACHMENT_CATEGORY"))) {
					newBean.setAttachmentCategory((String) param.get("ATTACHMENT_CATEGORY"));
				}
				// 封面类型
				if (null != param.get("ATTACHMENT_COVER_TYPE") && !"".equals(param.get("ATTACHMENT_COVER_TYPE"))) {
					newBean.setAttachmentCoverType((String) param.get("ATTACHMENT_COVER_TYPE"));
				}
				// 数据源
				if (null != param.get("DOC_DATASOURCE") && !"".equals(param.get("DOC_DATASOURCE"))) {
					newBean.setDocDatasource((String) param.get("DOC_DATASOURCE"));
				}
				// 电子文件服务器id
				if (null != param.get("DOC_SER_ID") && !"".equals(param.get("DOC_SER_ID"))) {
					newBean.setDocSerId((String) param.get("DOC_SER_ID"));
				}
				// 电子文件服务器名称
				if (null != param.get("DOC_SER_NAME") && !"".equals(param.get("DOC_SER_NAME"))) {
					newBean.setDocSerName((String) param.get("DOC_SER_NAME"));
				}
				// 存放相对路径
				if (null != param.get("DOC_SER_PATH") && !"".equals(param.get("DOC_SER_PATH"))) {
					newBean.setDocSerPath((String) param.get("DOC_SER_PATH"));
				}
				// 全文版本
				if (null != param.get("DOC_REL_VERSION") && !"".equals(param.get("DOC_REL_VERSION"))) {
					newBean.setDocRelVersion((String) param.get("DOC_REL_VERSION"));
				}
				// 真实性
				if (null != param.get("DOC_TRUE") && !"".equals(param.get("DOC_TRUE"))) {
					newBean.setDocTrue((String) param.get("DOC_TRUE"));
				}
				// 完整性
				if (null != param.get("DOC_INTEGRITY") && !"".equals(param.get("DOC_INTEGRITY"))) {
					newBean.setDocIntegrity((String) param.get("DOC_INTEGRITY"));
				}
				// 有效性
				if (null != param.get("DOC_VALID") && !"".equals(param.get("DOC_VALID"))) {
					newBean.setDocValid((String) param.get("DOC_VALID"));
				}
				// 指纹编码
				if (null != param.get("DOC_FINGER_CODE") && !"".equals(param.get("DOC_FINGER_CODE"))) {
					newBean.setDocFingerCode((String) param.get("DOC_FINGER_CODE"));
				}
				// 备注
				if (null != param.get("REMARK") && !"".equals(param.get("REMARK"))) {
					newBean.setRemark((String) param.get("REMARK"));
				}
				// 是否删除标识
				if (null != param.get("IF_DELETE") && !"".equals(param.get("IF_DELETE"))) {
					newBean.setIfDelete((String) param.get("IF_DELETE"));
				}
				// 全文描述
				if (null != param.get("ALL_DESCRIBE") && !"".equals(param.get("ALL_DESCRIBE"))) {
					newBean.setAllDescribe((String) param.get("ALL_DESCRIBE"));
				}
				// 附件OCR转换状态
				if (null != param.get("ATTRIBUTE_03") && !"".equals(param.get("ATTRIBUTE_03"))) {
					newBean.setAttribute03((String) param.get("ATTRIBUTE_03"));
				}
				// 稿本类型
				if (null != param.get("ATTRIBUTE_04") && !"".equals(param.get("ATTRIBUTE_04"))) {
					newBean.setAttribute04((String) param.get("ATTRIBUTE_04"));
				}
				// 是否扫描件
				if (null != param.get("ATTRIBUTE_05") && !"".equals(param.get("ATTRIBUTE_05"))) {
					newBean.setAttribute05((String) param.get("ATTRIBUTE_05"));
				}
				// 附件排序号
				if (null != param.get("ATTRIBUTE_11") && !"".equals(param.get("ATTRIBUTE_11"))) {
					newBean.setAttribute11(BigDecimal.valueOf(Long.parseLong(param.get("ATTRIBUTE_11").toString())));
				}
				SysLogUtil.log(newBean, oldBean, OpType.update, OpResult.success);
				PojoUtil.setSysProperties(newBean, OpType.update);
				this.hibernateDao.update(newBean);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据数据id和附件id判断关系表是否存在该数据
	 *
	 * @author 钟一华
	 * @param param
	 * @return
	 * @throws Exception
	 *             boolean
	 * @throws
	 */
	public boolean getDocRelationIsExistByParamByIntfs(Map<String, Object> param) throws Exception {
		String recordId = (String) param.get("RECORD_ID");
		String attachId = (String) param.get("ATTACHMENT_ID");
		String sql = "SELECT * FROM CBB_DOC_RELATION WHERE RECORD_ID = '" + recordId + "' AND ATTACHMENT_ID = '" + attachId + "'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		if (list.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获得附件编辑页面html
	 *
	 * @author 钟一华
	 * @return
	 * @throws Exception
	 *             List<Object[]>
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public List<Object[]> getAttachmentAndRelationAndUserDatas(String formId) throws Exception {
		String sql = "SELECT T.ID,\n" + "       T.ATTACH_NAME,\n" + "       T.ATTACH_SIZE,\n" + "       T.PARENT_TABLE_ID,\n" + "       T.PARENT_REGISTER_ID,\n" + "       DECODE(T.UPLOAD_PATH, NULL, 'TRUE', 'FALSE') SAVEDB,\n" + "       T.ATTACH_TYPE,\n"
				+ "       TO_CHAR(T.CREATION_DATE, 'YYYY-MM-DD') CREATION_DATE,\n" + "       R.SECRET_LEVEL,\n" + "       U.NAME,\n" + "       R.ATTACHMENT_COVER_TYPE\n" + "  FROM SYS_ATTACHMENT T\n" + "  LEFT JOIN SYS_USER U\n" + "    ON T.CREATED_BY = U.ID\n"
				+ "  LEFT JOIN CBB_DOC_RELATION R\n" + "  ON T.ID = R.ATTACHMENT_ID\n" + " WHERE R.RECORD_ID = '" + formId + "' AND R.IF_DELETE = 'N'\n" + " ORDER BY CREATION_DATE ASC, T.ATTACH_NAME ASC";
		List<Object[]> list = this.hibernateDao.findBySQL(sql);
		return list;
	}

	public List<Map<String, Object>> getAttachmentRelationByFormId(String formId) throws Exception {
		String sql = "SELECT CDR.* FROM CBB_DOC_RELATION CDR INNER JOIN SYS_ATTACHMENT SA ON SA.ID = CDR.ATTACHMENT_ID WHERE CDR.RECORD_ID = '" + formId + "' AND CDR.IF_DELETE = 'N'";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		return list;
	}

	/**
	 * 保存全文文件关系、保存文件缩略图
	 *
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void saveRelationAndMarker(Map<String, Object> parameter) throws Exception {
		String orgId = (String) parameter.get("orgId");
		String deptId = (String) parameter.get("deptId");
		String sysId = (String) parameter.get("sysId");
		String tableId = (String) parameter.get("tableId");
		String nodeId = (String) parameter.get("nodeId");
		String recordId = (String) parameter.get("recordId");
		String path = (String) parameter.get("path");
		String loginUserId = (String) parameter.get("loginUserId");
		String loginIp = (String) parameter.get("loginIp");
		// 获取附件信息
		String sql = "SELECT ATTACHMENT_ID FROM CBB_DOC_RELATION WHERE RECORD_ID = '" + recordId + "'";
		List<Object[]> list = this.hibernateDao.findBySQL(sql);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				// 附件ID
				String attachId = (String) list.get(i)[0];
				// 编辑页面，新上传的附件保存全文文件关系、保存文件缩略图。
				String sqlRelation = "SELECT ID, ATTACH_NAME, ATTACH_TYPE FROM SYS_ATTACHMENT WHERE ID = '" + attachId + "'";
				List<Map<String, Object>> attachList = this.jdbcAvicit.getJdbcTemplate().queryForList(sqlRelation);
				if (attachList.size() > 0) {
					Map<String, Object> map = attachList.get(0);
					// 附件名称
					String attachName = (String) map.get("ATTACH_NAME");
					// 附件类型
					String attachType = (String) map.get("ATTACH_TYPE");
					// 保存文件缩略图
					// flag（1：照片；2：视频；3：音频；4：其他）
					String flag = "4";
					if (attachType.equals("bmp") || attachType.equals("jpg") || attachType.equals("png") || attachType.equals("gif")) {
						flag = "1";
					} else if (attachType.equals("wmv")) {
						flag = "2";
					} else if (attachType.equals("mp3")) {
						flag = "3";
					}
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("attachName", attachName);
					params.put("attachId", attachId);
					params.put("recordId", recordId);
					params.put("nodeId", nodeId);
					params.put("tableId", tableId);
					params.put("loginUserId", loginUserId);
					params.put("loginIp", loginIp);
					params.put("attachType", attachType);
					this.savePic(orgId, deptId, sysId, flag, path, params);
					if ("1".equals(flag)) {
						// 保存预览图
						this.savePreviewPic(orgId, deptId, sysId, path, params);
					}
				}
			}
		}
	}

	/**
	 * 保存缩略图方法
	 * @param param
	 * @throws Exception void
	 * @throws
	 */
	public void saveSysMarker(String orgId, String deptId, String sysId, Map<String, Object> param) throws Exception {
		try {
			String attachType = (String) param.get("attachType");
			String attachName = (String) param.get("attachName");
			String attachId = (String) param.get("attachId");
			String recordId = (String) param.get("recordId");
			String nodeId = (String) param.get("nodeId");
			String tableId = (String) param.get("tableId");
			String loginUserId = (String) param.get("loginUserId");
			String loginIp = (String) param.get("loginIp");
			String path = (String) param.get("path");
			// 保存文件缩略图
			// flag（1：照片；2：视频；3：音频；4：其他）
			String flag = "4";
			if (attachType.equals("bmp") || attachType.equals("jpg") || attachType.equals("png") || attachType.equals("gif")) {
				flag = "1";
			} else if (attachType.equals("wmv")) {
				flag = "2";
			} else if (attachType.equals("mp3")) {
				flag = "3";
			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("attachName", attachName);
			params.put("attachId", attachId);
			params.put("recordId", recordId);
			params.put("nodeId", nodeId);
			params.put("tableId", tableId);
			params.put("loginUserId", loginUserId);
			params.put("loginIp", loginIp);
			params.put("attachType",attachType);
			this.savePic(orgId, deptId, sysId, flag, path, params);
			if ("1".equals(flag)) {
				// 保存预览图
				this.savePreviewPic(orgId, deptId, sysId, path, params);
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 删除全文文件关系、删除文件缩略图
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void deleteRelationAndMarker(Map<String, Object> parameter) {
		String attachId = (String) parameter.get("attachId");
		// 通过附件ID查询“全文文件关系表ID”
		//String docRelationId = "";
		String sql = "SELECT ID FROM CBB_DOC_RELATION R WHERE R.ATTACHMENT_ID = '" + attachId + "'";
		List list = this.hibernateDao.findBySQL(sql);
		if (list != null && list.size() > 0) {
			Object obj = list.get(0);
			if (obj != null && !obj.equals("")) {
				//docRelationId = (String) list.get(0);
			}
		}
		// 删除全文文件关系
		String delRelation = "DELETE FROM CBB_DOC_RELATION WHERE ATTACHMENT_ID = '" + attachId + "'";
		jdbcAvicit.getJdbcTemplate().execute(delRelation);
		// 删除文件缩略图
		String delMarker = "DELETE FROM CBB_SYS_MARKER WHERE SYS_ATTACHMENT_ID = '" + attachId + "'";
		jdbcAvicit.getJdbcTemplate().execute(delMarker);
	}

	/**
	 * 重新生成缩略图
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	@Override
	public void saveMarker(Map<String, Object> parameter) throws Exception {
		String orgId = (String) parameter.get("orgId");
		String deptId = (String) parameter.get("deptId");
		String sysId = (String) parameter.get("sysId");
		String tableId = (String) parameter.get("tableId");
		String nodeId = (String) parameter.get("nodeId");
		String path = (String) parameter.get("path");
		String ids = (String) parameter.get("ids");
		String recordId = (String) parameter.get("recordId");
		String loginUserId = (String) parameter.get("loginUserId");
		String loginIp = (String) parameter.get("loginIp");
		String[] idArray = ids.split(",");
		for (int i = 0; i < idArray.length; i++) {
			// 获取附件信息
			String sql = "SELECT S.ATTACH_NAME, S.ATTACH_TYPE, S.PARENT_REGISTER_ID\n" + " FROM SYS_ATTACHMENT S WHERE S.ID = '" + (String) idArray[i] + "'";
			List<Object[]> list = this.hibernateDao.findBySQL(sql);
			// 附件ID
			String attachId = (String) idArray[i];
			// 附件名称
			String attachName = "";
			// 附件类型
			String attachType = "";
			if (list != null && !list.equals("")) {
				if (list.get(0) != null && !list.get(0).equals("")) {
					attachName = (String) list.get(0)[0];
				}
				attachType = (String) list.get(0)[1];
			}
			// 重新生成缩略图，有文件缩略图记录时直接更新，无记录时直接新增。
			String sqlMarker = "SELECT M.ID FROM CBB_SYS_MARKER M WHERE M.SYS_ATTACHMENT_ID = '" + attachId + "'";
			List listMarker = this.hibernateDao.findBySQL(sqlMarker);
			// flag（1：照片；2：视频；3：音频；4：其他）
			String flag = "4";
			if (attachType.toLowerCase().equals("bmp") || attachType.toLowerCase().equals("jpg") || attachType.toLowerCase().equals("png") || attachType.toLowerCase().equals("gif")) {
				flag = "1";
			} else if (attachType.toLowerCase().equals("wmv")) {
				flag = "2";
			} else if (attachType.toLowerCase().equals("mp3")) {
				flag = "3";
			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("attachName", attachName);
			params.put("attachId", attachId);
			params.put("recordId", recordId);
			params.put("nodeId", nodeId);
			params.put("tableId", tableId);
			params.put("loginUserId", loginUserId);
			params.put("loginIp", loginIp);
			params.put("attachType", attachType);
			if (listMarker.size() == 0) {
				this.savePic(orgId, deptId, sysId, flag, path, params);
			} else {
				String markerId = "";
				Object obj1 = listMarker.get(0);
				if (obj1 != null && !obj1.equals("")) {
					markerId = listMarker.get(0).toString();
				}
				params.put("markerId", markerId);
				this.updatePic(orgId, deptId, sysId, flag, path, params);
			}
		}
	}

	/**
	 * 获取文件流
	 *
	 * @throws Exception
	 */
	@Override
	public byte[] getFileByte(Map<String, Object> param) throws Exception {
		String attachId = (String) param.get("attachId");
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		byte[] b = null;
		String sql = "SELECT M.MARKER_CONTENT FROM CBB_SYS_MARKER M WHERE M.SYS_ATTACHMENT_ID = '" + attachId + "'";
		try {
			conn = jdbcAvicit.getJdbcTemplate().getDataSource().getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				b = rs.getBytes(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("数据库操作异常，请联系管理员！");
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return b;
	}

	/**
	 * 修改是否封面
	 */
	@Override
	public void updateCoverType(Map<String, String> oldFileMap, String mongoId) {
		Iterator<String> it = oldFileMap.keySet().iterator();
		while (it.hasNext()) {
			String ids = it.next();
			String coverType = oldFileMap.get(ids);
			String[] idArray = ids.split("_");

			String sql = "UPDATE CBB_DOC_RELATION R SET R.ATTACHMENT_COVER_TYPE = '" + coverType + "'\n" + " WHERE R.ATTACHMENT_ID = '" + idArray[0] + "' AND R.RECORD_ID = '" + idArray[1] + "'";
			this.jdbcAvicit.getJdbcTemplate().update(sql);
		}
	}

	/**
	 * 保存图片
	 *
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param flag
	 *            （1：照片；2：视频；3：音频；4：其他）
	 * @param params
	 * @throws Exception
	 */
	@Override
	public void savePic(String orgId, String deptId, String sysId, String flag, String path, Map<String, Object> params) throws Exception {
		try {
			String attachmentId = (String) params.get("attachId");
			String attachType = (String) params.get("attachType");
			// 获取存储方式
			InputStream is = getAttachmentInputStream(attachmentId, sysId);
			// is = mongoDBManager.getMongoDBController("LANTOP").getGridFSIOById(attachmentId);
			if (null != is) {
				// 如果文档类型是照片
				if ("1".equals(flag)) {
					String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + attachmentId + ".jpg";
					int outWidth = 160;
					int outHeight = 120;
					// float scale = 0f;
					int rotate = 0;
					this.chreatePictureChange(is, fileOutPath, outWidth, outHeight, null, rotate);
					// 指定文件路径
					// String thumbnailPath =
					String thumbnailPath = fileOutPath;
					InputStream isfile = new FileInputStream(thumbnailPath);
					// 保存缩略图
					this.saveThumToDb(orgId, deptId, sysId, isfile, params);
				} else if ("2".equals(flag)) {
					final InputStream isFinal = is;
					final String attIdFinal = attachmentId;
					final String orgIdFinal = orgId;
					final String deptIdFinal = deptId;
					final String sysIdFinal = sysId;
					final Map<String, Object> parameter = params;
					final String pathFinal = path;
					if ("/".equals(File.separator)) {
						String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + "yinpin.jpg";
						String thumbnailPath = fileOutPath;
						InputStream isfile = new FileInputStream(thumbnailPath);
						// 保存缩略图
						this.saveThumToDb(orgId, deptId, sysId, isfile, params);
					} else {
						// 新建线程
						Thread t = new Thread() {

							public void run() {
								try {
									parameter.put("PATH", pathFinal);
									saveFileToDir(isFinal, attIdFinal, orgIdFinal, deptIdFinal, sysIdFinal, parameter);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						};
						t.start();
					}
				} else if ("3".equals(flag)) {
					String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + "yinpin.jpg";
					String thumbnailPath = fileOutPath;
					InputStream isfile = new FileInputStream(thumbnailPath);
					// 保存缩略图
					this.saveThumToDb(orgId, deptId, sysId, isfile, params);
				} else {
					// 其他类型图片暂定为 tx.jpg
					String txPath = path + File.separator + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "custom" + File.separator + "img" + File.separator + "tx.jpg";
					InputStream txFile = new FileInputStream(txPath);
					String fileOutPath = path + File.separator + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + "tx.jpg";
					int outWidth = 160;
					int outHeight = 120;
					// float scale = 0f;
					int rotate = 0;
					this.chreatePictureChange(txFile, fileOutPath, outWidth, outHeight, null, rotate);
					// 指定文件路径
					String thumbnailPath = fileOutPath;
					InputStream isfile = new FileInputStream(thumbnailPath);
					// 保存缩略图
					this.saveThumToDb(orgId, deptId, sysId, isfile, params);
				}
			}
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 处理视频缩略图
	 *
	 * @param vedioPath
	 * @param ffmpegPath
	 * @param thumbnailPath
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean processImg(String vedioPath, String ffmpegPath, String thumbnailPath) throws Exception {
		File file = new File(vedioPath);
		if (!file.exists()) {
			System.err.println("路径[" + vedioPath + "]对应的视频文件不存在!");
			return false;
		}
		List<String> commands = new ArrayList<String>();
		commands.add(ffmpegPath);
		commands.add("-i");
		commands.add(vedioPath);
		commands.add("-y");
		commands.add("-f");
		commands.add("image2");
		commands.add("-ss");
		commands.add("8");// 这个参数是设置截取视频多少秒时的画面
		// commands.add("-t");
		// commands.add("0.001");
		commands.add("-s");
		commands.add("160x120");
		// commands.add(vedio_path.substring(0,
		// vedio_path.lastIndexOf(".")).replaceFirst("vedio", "file") + ".jpg");
		commands.add(thumbnailPath);
		try {
			ProcessBuilder builder = new ProcessBuilder();
			builder.command(commands);
			builder.start();
			// System.out.println("截取成功");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 图片缩略图切割 --- 根据文件地址 生成图片缩略图
	 *
	 * @param fileFromPath
	 *            图片源文件地址
	 * @param fileOutPath
	 *            图片缩略图地址
	 * @param outWidth
	 *            图片缩略图宽度
	 * @param outHeight
	 *            图片缩略图高度
	 * @param scale
	 *            缩放比例
	 * @param rotate
	 *            旋转度数
	 * @return
	 */
	@Override
	public void chreatePictureChange(String fileFromPath, String fileOutPath, Integer outWidth, Integer outHeight, Float scale, Integer rotate) throws Exception {
		Builder<File> builder = (Builder<File>) Thumbnails.of(fileFromPath);
		if (null != outWidth && null == outHeight) {
			builder.width(outWidth);
		}
		if (null == outWidth && null != outHeight) {
			builder.height(outHeight);
		}
		if (null != outWidth && null != outHeight) {
			builder.size(outWidth, outHeight);
		}
		if (null != scale) {
			builder.scale(scale);
		}
		if (null != rotate) {
			builder.rotate(rotate);
		}
		builder.toFile(fileOutPath);
	}

	/**
	 * 图片缩略图切割 --- 根据文件流 生成图片缩略图
	 *
	 * @param fileFrom
	 *            图片源文件地址
	 * @param fileOutPath
	 *            图片缩略图地址
	 * @param outWidth
	 *            图片缩略图宽度
	 * @param outHeight
	 *            图片缩略图高度
	 * @param scale
	 *            缩放比例
	 * @param rotate
	 *            旋转度数
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void chreatePictureChange(InputStream fileFrom, String fileOutPath, Integer outWidth, Integer outHeight, Float scale, Integer rotate) throws Exception {
		//Boolean pictureChangeResult = false;
		try {
			if (null != fileFrom) {
				Builder<InputStream> builder = (Builder<InputStream>) Thumbnails.of(fileFrom);
				if (null != outWidth && null == outHeight) {
					builder.width(outWidth);
				}
				if (null == outWidth && null != outHeight) {
					builder.height(outHeight);
				}
				if (null != outWidth && null != outHeight) {
					builder.size(outWidth, outHeight);
				}
				if (null != scale) {
					builder.scale(scale);
				}
				if (null != rotate) {
					builder.rotate(rotate);
				}
				builder.outputQuality(1.0d);
				builder.toFile(fileOutPath);
				//pictureChangeResult = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != fileFrom) {
				fileFrom.close();
			}
		}
	}

	/**
	 * 保存文件至项目目录
	 *
	 * @param fileFrom
	 * @param attId
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @return
	 * @throws Exception
	 */
	@Override
	public void saveFileToDir(InputStream fileFrom, String attId, String orgId, String deptId, String sysId, Map<String, Object> params) throws Exception {
		Map<String, Object> pa = params;
		String path = (String) pa.get("PATH");
		String proPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia";
		String dest = proPath + File.separator + "videotemp" + File.separator + attId + ".wmv";
		File file = new File(dest);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream out = new FileOutputStream(file);
		// int c;
		// byte buffer[] = new byte[1024];
		byte[] b = IOUtils.toByteArray(fileFrom);
		// while((c = fileFrom.read(buffer)) != -1){
		// for(int i = 0; i < c; i++)
		// out.write(buffer[i]);
		// }
		out.write(b);
		fileFrom.close();
		out.close();

		// 抓取缩略图
		String ffmpegPath = proPath + File.separator + "ffmpeg" + File.separator + "ffmpeg.exe";
		String thumbnailPath = proPath + File.separator + "thumbnail";
		processImg(dest, ffmpegPath, thumbnailPath + File.separator + attId + ".jpg");
		Thread.sleep(30000);

		// 将缩略图存至数据库
		// String thumId = ComUtil.getId();
		File infile = new File(thumbnailPath + File.separator + attId + ".jpg");
		if (!infile.exists()) {
			infile.createNewFile();
		}
		InputStream is = new FileInputStream(infile);
		this.saveThumToDb(orgId, deptId, sysId, is, params);
		File fileDest = new File(dest);
		// 删除临时文件
		if (fileDest.exists()) {
			fileDest.delete();
		}
	}

	/**
	 * 保存缩略图至数据库
	 *
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param is
	 * @param params
	 * @throws Exception
	 */
	@Override
	public void saveThumToDb(String orgId, String deptId, String sysId, InputStream is, Map<String, Object> params) throws Exception {
		String attachName = (String) params.get("attachName");
		//String recordId = (String) params.get("recordId");
		//String nodeId = (String) params.get("nodeId");
		String attachId = (String) params.get("attachId");
		//String tableId = (String) params.get("tableId");
		String thumId = ComUtil.getId();
		String loginUserId = (String) params.get("loginUserId");
		String loginIp = (String) params.get("loginIp");
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = this.jdbcAvicit.getJdbcTemplate().getDataSource().getConnection();
			String insertsql = "INSERT INTO CBB_SYS_MARKER(ID,MARKER_TITILE,SYS_ATTACHMENT_ID,MARKER_CONTENT,HIT_COUNT,REMARK,ORG_ID,DEPT_ID,SYS_ID,SECRET_LEVEL,SYS_APPLICATION_ID,LAST_UPDATE_DATE,LAST_UPDATED_BY,CREATION_DATE,CREATED_BY,LAST_UPDATE_IP,VERSION)"
					+ " VALUES('"
					+ thumId
					+ "','"
					+ attachName
					+ "','"
					+ attachId
					+ "',empty_blob(),0,'','"
					+ orgId
					+ "','"
					+ deptId
					+ "','"
					+ sysId
					+ "',1,1,sysdate,'"
					+ loginUserId
					+ "',sysdate,'"
					+ loginUserId
					+ "','"
					+ loginIp
					+ "',0)";// 首先插入一个空的Blob类型
			// conn.setAutoCommit(false);
			stmt = conn.createStatement();
			int rt = stmt.executeUpdate(insertsql);
			if (rt > 0) {
				String preCursor = "SELECT ID,MARKER_CONTENT FROM CBB_SYS_MARKER WHERE ID ='" + thumId + "' FOR UPDATE";
				rs = stmt.executeQuery(preCursor);// 锁定列
				rs.next();
				Blob b = (Blob) rs.getBlob("MARKER_CONTENT");
				BufferedOutputStream bos = new BufferedOutputStream(b.setBinaryStream(0L));
				BufferedInputStream bis = new BufferedInputStream(is);
				int bytes;
				try {
					while ((bytes = bis.read()) != -1) {
						bos.write(bytes);
					}
					bis.close();
					bos.close();
					conn.commit();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			conn.rollback();
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					// conn.setAutoCommit(true);
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 保存图片 baibin
	 *
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param flag
	 *            （1：照片；2：视频；3：音频；4：其他）
	 * @param params
	 * @throws Exception
	 */
	@Override
	public void updatePic(String orgId, String deptId, String sysId, String flag, String path, Map<String, Object> params) throws Exception {
		String attachmentId = (String) params.get("attachId");
		String attachType =(String) params.get("attachType");
		// 定义输入流 ，从MongoDB获取文档信息
		InputStream is = getAttachmentInputStream(attachmentId, sysId);
		if (null != is) {
			// 如果文档类型是照片
			if ("1".equals(flag)) {
				String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + attachmentId + ".jpg";
				int outWidth = 160;
				int outHeight = 120;
				// float scale = 0f;
				int rotate = 0;
				this.chreatePictureChange(is, fileOutPath, outWidth, outHeight, null, rotate);
				// 指定文件路径
				// String thumbnailPath =
				String thumbnailPath = fileOutPath;
				InputStream isfile = new FileInputStream(thumbnailPath);
				// 保存缩略图
				this.updateThumToDb(orgId, deptId, sysId, isfile, params);
			} else if ("2".equals(flag)) {
				final InputStream isFinal = is;
				final String attIdFinal = attachmentId;
				final String orgIdFinal = orgId;
				final String deptIdFinal = deptId;
				final String sysIdFinal = sysId;
				final Map<String, Object> parameter = params;
				if ("/".equals(File.separator)) {
					String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + "yinpin.jpg";
					String thumbnailPath = fileOutPath;
					InputStream isfile = new FileInputStream(thumbnailPath);
					// 保存缩略图
					this.updateThumToDb(orgId, deptId, sysId, isfile, params);
				} else {
					// 新建线程
					Thread t = new Thread() {

						public void run() {
							try {
								saveFileToDir(isFinal, attIdFinal, orgIdFinal, deptIdFinal, sysIdFinal, parameter);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};
					t.start();
				}
			} else if ("3".equals(flag)) {
				String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + "yinpin.jpg";
				String thumbnailPath = fileOutPath;
				InputStream isfile = new FileInputStream(thumbnailPath);
				// 保存缩略图
				this.updateThumToDb(orgId, deptId, sysId, isfile, params);
			} else {
				// 其他类型图片暂定为 tx.jpg
				String txPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "custom" + File.separator + "img" + File.separator + "tx.jpg";
				InputStream txFile = new FileInputStream(txPath);
				String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "thumbnail" + File.separator + "tx.jpg";
				int outWidth = 160;
				int outHeight = 120;
				// float scale = 0f;
				int rotate = 0;
				this.chreatePictureChange(txFile, fileOutPath, outWidth, outHeight, null, rotate);
				// 指定文件路径
				String thumbnailPath = fileOutPath;
				InputStream isfile = new FileInputStream(thumbnailPath);
				// 保存缩略图
				this.updateThumToDb(orgId, deptId, sysId, isfile, params);
			}
		}
	}

	/**
	 * 保存缩略图至数据库 baibin
	 *
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param is
	 * @param params
	 * @throws Exception
	 */
	@Override
	public void updateThumToDb(String orgId, String deptId, String sysId, InputStream is, Map<String, Object> params) throws Exception {
		String thumId = (String) params.get("markerId");
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = this.jdbcAvicit.getJdbcTemplate().getDataSource().getConnection();
			// 首先插入一个空的Blob类型
			// conn.setAutoCommit(false);
			stmt = conn.createStatement();
			String preCursor = "SELECT ID,MARKER_CONTENT FROM CBB_SYS_MARKER WHERE ID ='" + thumId + "' FOR UPDATE";
			rs = stmt.executeQuery(preCursor);// 锁定列
			rs.next();
			Blob b = (Blob) rs.getBlob("MARKER_CONTENT");
			BufferedOutputStream bos = new BufferedOutputStream(b.setBinaryStream(0L));
			BufferedInputStream bis = new BufferedInputStream(is);
			int bytes;
			try {
				while ((bytes = bis.read()) != -1) {
					bos.write(bytes);
				}
				bis.close();
				bos.close();
				conn.commit();
			} catch (IOException e) {
				conn.rollback();
				e.printStackTrace();
			}
			// }
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (stmt != null) {
					stmt.close();
				}
				if (conn != null) {
					// conn.setAutoCommit(true);
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 保存预览图片
	 *
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param path
	 * @param params
	 * @throws Exception
	 */
	@Override
	public void savePreviewPic(String orgId, String deptId, String sysId, String path, Map<String, Object> params) throws Exception {
		try {
			String attachmentId = (String) params.get("attachId");
			String attachType = (String)params.get("attachType");
			// 定义输入流 ，从MongoDB获取文档信息
			InputStream in = getAttachmentInputStream(attachmentId, sysId);
			// is = mongoDBManager.getMongoDBController("LANTOP").getGridFSIOById(attachmentId);
			String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "preview" + File.separator + attachmentId + ".jpg";
			int outWidth = 800;
			int outHeight = 600;
			// float scale = 0f;
			int rotate = 0;
			this.chreatePictureChange(in, fileOutPath, outWidth, outHeight, null, rotate);
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	/**
	 * 删除附件各类数据(附件表,mongdb表,relation表,marker表)
	 *
	 * @author 钟一华
	 * @param param
	 *            ( sysId: 系统标识 attachId: 附件id)
	 * @throws Exception
	 *             void
	 * @throws
	 */
	@Override
	public void deleteAttachByAttachIdAndSysId(Map<String, Object> param) throws Exception {

	}

	/**
	 * 通过数据id获取附件信息集合
	 */
	public List<Map<String, Object>> getAttachmentsByRecordId(String recordId) throws Exception {
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT SA.ID,\n");
		sbSql.append("       SA.ATTACH_NAME,\n");
		sbSql.append("       SA.PARENT_TABLE_ID,\n");
		sbSql.append("       SA.PARENT_REGISTER_ID,\n");
		sbSql.append("       SA.ATTACH_TYPE,\n");
		sbSql.append("       SA.ATTACH_SIZE,\n");
		sbSql.append("       SA.LAST_UPDATE_DATE,\n");
		sbSql.append("       SA.LAST_UPDATED_BY,\n");
		sbSql.append("       SA.LAST_UPDATE_IP,\n");
		sbSql.append("       CDR.CREATION_DATE,\n");
		sbSql.append("       CDR.CREATED_BY,\n");
		sbSql.append("       SA.VERSION,\n");
		sbSql.append("       SA.ATTRIBUTE_01,\n");
		sbSql.append("       SA.ATTRIBUTE_02,\n");
		sbSql.append("       SA.ATTRIBUTE_03,\n");
		sbSql.append("       SA.ATTRIBUTE_04,\n");
		sbSql.append("       SA.ATTRIBUTE_05,\n");
		sbSql.append("       SA.ATTRIBUTE_06,\n");
		sbSql.append("       SA.ATTRIBUTE_07,\n");
		sbSql.append("       SA.ATTRIBUTE_08,\n");
		sbSql.append("       SA.ATTRIBUTE_09,\n");
		sbSql.append("       SA.ATTRIBUTE_10,\n");
		sbSql.append("       SA.UPLOAD_PATH,\n");
		sbSql.append("       SA.PARENT_TABLE_FIELD,\n");
		sbSql.append("       SA.ATTACH_CATEGORY,\n");
		sbSql.append("       SA.FASTDFS_LOCATION,\n");
		sbSql.append("       CDR.RECORD_ID,\n");
		sbSql.append("       CDR.ARCHIVE_TABLE_ID,\n");
		sbSql.append("       CDR.ATTACHMENT_CATEGORY,\n");
		sbSql.append("       CDR.ATTACHMENT_COVER_TYPE,\n");
		sbSql.append("       CDR.SECRET_LEVEL\n");
		sbSql.append("  FROM CBB_DOC_RELATION CDR\n");
		sbSql.append("  LEFT JOIN SYS_ATTACHMENT SA\n");
		sbSql.append("    ON SA.ID = CDR.ATTACHMENT_ID\n");
		sbSql.append(" WHERE CDR.RECORD_ID = '" + recordId + "'\n");
		sbSql.append(" ORDER BY CDR.CREATION_DATE DESC, SA.ATTACH_NAME ASC");
		List<Map<String, Object>> attachs = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
		return attachs;
	}

	/**
	 * 通过数据id, 上传类型获取附件信息集合
	 */
	public List<Map<String, Object>> getAttachmentsByRecordIdByUploadFlag(String recordId, String uploadFlag) throws Exception {
		String sql = "SELECT SA.ID,SA.ATTACH_NAME,SA.PARENT_TABLE_ID,SA.PARENT_REGISTER_ID,SA.ATTACH_TYPE,SA.ATTACH_SIZE,SA.LAST_UPDATE_DATE,SA.LAST_UPDATED_BY,SA.LAST_UPDATE_IP,SA.CREATION_DATE,SA.CREATED_BY,SA.VERSION,SA.ATTRIBUTE_01,SA.ATTRIBUTE_02,SA.ATTRIBUTE_03,SA.ATTRIBUTE_04,SA.ATTRIBUTE_05,SA.ATTRIBUTE_06,SA.ATTRIBUTE_07,SA.ATTRIBUTE_08,SA.ATTRIBUTE_09,SA.ATTRIBUTE_10,SA.UPLOAD_PATH,SA.PARENT_TABLE_FIELD,SA.ATTACH_CATEGORY,SA.SECRET_LEVEL,SA.FASTDFS_LOCATION FROM SYS_ATTACHMENT SA INNER JOIN CBB_DOC_RELATION CDR ON SA.ID = CDR.ATTACHMENT_ID WHERE SA.PARENT_REGISTER_ID = '"
				+ recordId + "'  AND CDR.ATTRIBUTE_01 = '" + uploadFlag + "' AND SA.ATTRIBUTE_10 = 'N' ORDER BY SA.CREATION_DATE, SA.ATTACH_NAME ASC";
		List<Map<String, Object>> attachs = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		return attachs;
	}

	/**
	 * 通过数据id获得附件id
	 */
	public List<Map<String, Object>> getAttachByRecordId(String recordId) throws Exception {
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT ID, ATTACH_NAME, ATTACH_TYPE FROM SYS_ATTACHMENT WHERE ID IN (SELECT ATTACHMENT_ID FROM CBB_DOC_RELATION WHERE RECORD_ID = ? AND IF_DELETE = 'N')");
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString(), new Object[] {recordId});
		return list;
	}

	/**
	 * 通过数据id获得附件id(根据上传类型过滤)
	 */
	public List<Map<String, Object>> getAttachIdByrecordIdByUploadFlag(String recordId, String uploadFlag) throws Exception {
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("SELECT SA.ID,SA.ATTACH_NAME,SA.PARENT_TABLE_ID,SA.PARENT_REGISTER_ID,SA.ATTACH_TYPE,SA.ATTACH_SIZE,SA.LAST_UPDATE_DATE,SA.LAST_UPDATED_BY,SA.LAST_UPDATE_IP,SA.CREATION_DATE,SA.CREATED_BY,SA.VERSION,SA.ATTRIBUTE_01,SA.ATTRIBUTE_02,SA.ATTRIBUTE_03,SA.ATTRIBUTE_04,SA.ATTRIBUTE_05,SA.ATTRIBUTE_06,SA.ATTRIBUTE_07,SA.ATTRIBUTE_08,SA.ATTRIBUTE_09,SA.ATTRIBUTE_10,SA.UPLOAD_PATH,SA.PARENT_TABLE_FIELD,SA.ATTACH_CATEGORY,SA.SECRET_LEVEL,SA.FASTDFS_LOCATION FROM SYS_ATTACHMENT SA\n");
		sbSql.append("LEFT JOIN CBB_DOC_RELATION CDR ON SA.ID = CDR.ATTACHMENT_ID\n");
		sbSql.append("WHERE CDR.IF_DELETE = 'N' AND CDR.RECORD_ID = '" + recordId + "' AND CDR.ATTRIBUTE_01 = '" + uploadFlag + "'");
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
		return list;
	}

	/**
	 * @author 钟一华
	 * @param fileList
	 * @param param
	 * @param mongoId
	 * @return String
	 * @throws
	 */
	public String saveAttachmentByFileList(List<File> fileList, Map<String, Object> param, String mongoId) {
		// 获取存储方式
		String businessId = (String) param.get("businessId");
		String path = (String) param.get("path");//临时文件路径
		String businessTableName = "pm_project";// (String) param.get("businessTableName");
		String category = (String) param.get("category");
		String secretLevel = (String) param.get("secretLevel");
		// 0成功 , 1 失败
		String fileStatus = "";
		String fileId = "";
		for (int i = 0; i < fileList.size(); i++) {
			try {
				File temp = fileList.get(i);
				SysFileUpload sysFileUpload = new SysFileUpload();
				sysFileUpload.setId(ComUtil.getId());
				sysFileUpload.setFILE_NAME(temp.getName());
				sysFileUpload.setFILE_BUSINESS_ID(businessId);
				sysFileUpload.setFILE_BUSINESS_TABLE_NAME(businessTableName);
				sysFileUpload.setFILE_SIZE(temp.length());
				sysFileUpload.setFILE_TYPE(FileUtil.getFileExtensionName(temp.getName()));
				sysFileUpload.setATTACH_CATEGORY(category);
				sysFileUpload.setSECRET_LEVEL(secretLevel);
				if (param.containsKey("attribute05") && null != param.get("attribute05") && !"".equals(param.get("attribute05")) && !"null".equals(param.get("attribute05"))) {
					sysFileUpload.setATTRIBUTE_05(param.get("attribute05").toString());
				}
				if (param.containsKey("attribute06") && null != param.get("attribute06") && !"".equals(param.get("attribute06")) && !"null".equals(param.get("attribute06"))) {
					sysFileUpload.setATTRIBUTE_06(param.get("attribute06").toString());
				}
				if (param.containsKey("attribute07") && null != param.get("attribute07") && !"".equals(param.get("attribute07")) && !"null".equals(param.get("attribute07"))) {
					sysFileUpload.setATTRIBUTE_07(param.get("attribute07").toString());
				}
				if (param.containsKey("attribute08") && null != param.get("attribute08") && !"".equals(param.get("attribute08")) && !"null".equals(param.get("attribute08"))) {
					sysFileUpload.setATTRIBUTE_08(param.get("attribute08").toString());
				}
				if (param.containsKey("attribute09") && null != param.get("attribute09") && !"".equals(param.get("attribute09")) && !"null".equals(param.get("attribute09"))) {
					sysFileUpload.setATTRIBUTE_09(param.get("attribute09").toString());
				}
				sysFileUploadService.insertSysFileUpload(sysFileUpload);
				fileId = sysFileUpload.getId();//S3文件名称
				fileId = fileId+"."+sysFileUpload.getFILE_TYPE();
				System.out.println("附件上传对象存储时的文件名: "+fileId);
				//S3文件上传方法
				getS3Service().upload(getS3(), bucketName, "main_data" + File.separator + fileId, path);
				Boolean b= this.getS3Service().isObjExist(getS3(), bucketName,"main_data"+File.separator+fileId);//查询是否存在文件
				if(b){
					File delfile = new File(path);
					delfile.delete();
				}else{
					System.out.println("附件"+fileId+"上传对象存储失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return fileId;
	}

	/**
	 * 通过数据id获得附件集合
	 */
	public List<Map<String, Object>> getAttachDatasByRecordId(String recordId) throws Exception {
		String sql = "SELECT ID,ATTACH_NAME,PARENT_TABLE_ID,PARENT_REGISTER_ID,ATTACH_TYPE,ATTACH_SIZE,LAST_UPDATE_DATE,LAST_UPDATED_BY,LAST_UPDATE_IP,CREATION_DATE,CREATED_BY,VERSION,ATTRIBUTE_01,ATTRIBUTE_02,ATTRIBUTE_03,ATTRIBUTE_04,ATTRIBUTE_05,ATTRIBUTE_06,ATTRIBUTE_07,ATTRIBUTE_08,ATTRIBUTE_09,ATTRIBUTE_10,UPLOAD_PATH,PARENT_TABLE_FIELD,ATTACH_CATEGORY,SECRET_LEVEL,FASTDFS_LOCATION FROM SYS_ATTACHMENT WHERE ID IN (SELECT ATTACHMENT_ID FROM CBB_DOC_RELATION WHERE RECORD_ID = '"
				+ recordId + "' AND IF_DELETE = 'N')";
		List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		return list;
	}

	/**
	 * 通过附件id,sysId,存储类型获取附件流
	 */
	public InputStream getAttachmentInputStream(String attachId, String sysId) {
		InputStream in = null;
		try {
			// 获取存储方式
			String saveType = JProperties.getFileProperties("savetype");

			if (saveType != null && !"".equals(saveType) && "database".equals(saveType)) {// 数据库
				in = docService.getFileByDatabase(attachId);
			} else if (saveType != null && !"".equals(saveType) && "disk".equals(saveType)) {// 磁盘
				in = docService.getFileByDisk(attachId);
			} else if (saveType != null && !"".equals(saveType) && "fastdfs".equals(saveType)) {// fastdfs

			} else if (saveType != null && !"".equals(saveType) && "mongodb".equals(saveType)) {// mongodb
				in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(attachId);
			}  else if (saveType != null && !"".equals(saveType) && "s3".equals(saveType)) {// mongodb
//				//获取文件后缀
				String userHome = System.getProperty("user.home");
				String filePath = userHome + File.separator;
				//SanXiaFiles update 2019-12-08 huangjian start
				List<Map<String, Object>> attList = jdbcAvicit.getJdbcTemplate().queryForList("SELECT SA.ATTACH_TYPE FROM SYS_ATTACHMENT SA WHERE SA.ID = '" + attachId + "' ");
				if(null != attList && attList.size() > 0){
					String fix = String.valueOf(attList.get(0).get("ATTACH_TYPE")).toLowerCase();
					//SanXiaFiles update 2019-12-08 huangjian end
					getS3Service().download(getS3(), bucketName, folderName + "/" + attachId+"."+fix, filePath);
					String filePaths = filePath + attachId+"."+fix;
					in = new FileInputStream(filePaths);
					File fs = new File(filePaths);
				}
			}else {
				in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(attachId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;
	}

	/**
	 * 通过附件id,sysId,存储类型获取附件流
	 */
	public InputStream getAttachmentInputStream(String attachId, String sysId, HttpServletResponse response) {
		InputStream in = null;
		try {
			// 获取存储方式
			String saveType = JProperties.getFileProperties("savetype");

			if (saveType != null && !"".equals(saveType) && "database".equals(saveType)) {// 数据库
				in = docService.getFileByDatabase(attachId);
			} else if (saveType != null && !"".equals(saveType) && "disk".equals(saveType)) {// 磁盘
				in = docService.getFileByDisk(attachId);
			} else if (saveType != null && !"".equals(saveType) && "fastdfs".equals(saveType)) {// fastdfs
				in = new ByteArrayInputStream(docService.getFileByFastdfs(attachId));
				BufferedOutputStream bout = new BufferedOutputStream(response.getOutputStream());
				try {
					if (null != in) {
						byte b[] = new byte[4096];
						int len = in.read(b);
						while (len > 0) {
							bout.write(b, 0, len);
							len = in.read(b);
						}
					}
				} catch (IOException e) {
					if (!e.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
						throw e;
					}
				} finally {
					if (null != bout) {
						bout.close();
					}
					if (null != in) {
						in.close();
					}
				}
			} else if (saveType != null && !"".equals(saveType) && "mongodb".equals(saveType)) {// mongodb
				in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(attachId);
			}else if (saveType != null && !"".equals(saveType) && "s3".equals(saveType)) {// mongodb
				//获取文件后缀的attachId
//				in = getS3Service().getObjectInputStream(getS3(),bucketName,//桶名
//						folderName+"/"+attachId);//文件夹名
				String userHome = System.getProperty("user.home");
				String filePath = userHome + File.separator;
				getS3Service().download(getS3(), bucketName, folderName + "/" + attachId, filePath);
				String filePaths = filePath + attachId;
				in = new FileInputStream(filePaths);
				File fs = new File(filePaths);
			}else {
				in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(attachId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
		}
		return in;
	}

	/**
	 * 流转byte数组
	 * @param in
	 * @return
	 * @throws Exception byte[]
	 * @throws
	 */
	public byte[] toByteArray(InputStream in) throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}

	/**
	 * 将音频文件保存到音频临时文件夹中
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param list
	 * @param path
	 * @throws Exception void
	 * @throws
	 */
	public void saveAudioFileToProjectByIntfs(String orgId, String deptId, String sysId, List<Map<String, Object>> list, String path) throws Exception {

		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			String attachmentId = (String) map.get("ID");
			String attachType = (String) map.get("ATTACH_TYPE");
			String fileOutPath = path + "avicit" + File.separator + "im" + File.separator + "lantop" + File.separator + "common" + File.separator + "multimedia" + File.separator + "audiotemp" + File.separator + attachmentId + "." + attachType;
			// 获取附件流文件
			InputStream in = getAttachmentInputStream(attachmentId, sysId);
			File file = new File(fileOutPath);
			try {
				FileOutputStream fop = new FileOutputStream(file);
				if (!file.exists()) {
					file.createNewFile();
				}
				// 将文件流转成byte数组
				byte[] contentInBytes = this.toByteArray(in);
				// 将byte数组 写入指定文件夹的文件中
				fop.write(contentInBytes);
				fop.flush();
				fop.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 保存附件信息
	 * @param orgId
	 * @param deptId
	 * @param sysId
	 * @param files
	 * @param param
	 * @throws Exception void
	 * @throws
	 */
	public void saveAttachmentBySaveTypeByIntfs(String orgId, String deptId, String sysId, List<File> files, Map<String, Object> param) throws Exception {
		// 获取存储方式
		String saveType = JProperties.getFileProperties("savetype");
		String businessId = (String) param.get("businessId");
		String businessTableName = "pm_project";// (String) param.get("businessTableName");
		String category = (String) param.get("category");
		String secretLevel = (String) param.get("secretLevel");
		String mongoId = (String) param.get("mongoId");
		String uploadType = (String) param.get("uploadType");
		String tableId = (String) param.get("tableId");
		String userId = (String) param.get("userId");
		String loginIp = (String) param.get("loginIp");
		String nodeId = (String) param.get("nodeId");
		String useCount = (String) param.get("useCount");
		String attachSaveId = (String) param.get("attachSaveId");
		// 唯一验证id
		String uniqueId = (String) param.get("unique_id");
		String attachmentSaveName = (String) param.get("attachmentSaveName");
		CommonHibernateDao2 hibernateDao = SpringFactory.getBean(CommonHibernateDao2.class);
		LobHelper lobHelper = hibernateDao.getSession().getLobHelper();
		FileInputStream stream = null;
		ByteArrayOutputStream out = null;
		OutputStream os = null;
		BufferedInputStream is = null;
		try {
			for (int i = 0; i < files.size(); i++) {
				File temp = files.get(i);
				SysFileUpload sysFileUpload = new SysFileUpload();
				String attachId = ComUtil.getId();
				sysFileUpload.setId(attachId);
				sysFileUpload.setFILE_NAME(attachmentSaveName);
				stream = new FileInputStream(temp);
				out = new ByteArrayOutputStream(4096);
				if (saveType != null && !"".equals(saveType) && "database".equals(saveType)) {// database
					byte[] b = new byte[4096];
					int n;
					while ((n = stream.read(b)) != -1) {
						out.write(b, 0, n);
					}
					Blob fileBody = lobHelper.createBlob(out.toByteArray());
					sysFileUpload.setFILE_BODY(fileBody);
				} else if (saveType != null && !"".equals(saveType) && "disk".equals(saveType)) {// disk
					this.uploadDir = new File(SwfUploadServlet.DOCCENTERPATH);
					if (!this.uploadDir.exists()) {
						uploadDir.mkdirs();
					}
					String fileName = FileUtil.getDoccenterDir(this.uploadDir.getAbsolutePath(), businessTableName, businessId) + FileUtil.getSep() + temp.getName();
					// 写入服务器磁盘
					File file = new File(fileName);
					os = new FileOutputStream(file);
					is = new BufferedInputStream(stream);
					byte[] b = new byte[4096];
					int n;
					while ((n = is.read(b)) != -1) {
						os.write(b, 0, n);
					}
					sysFileUpload.setFILE_URL(fileName);
				} else if (saveType != null && !"".equals(saveType) && "fastdfs".equals(saveType)) {// fastdfs
					String res = null;
					res = FastDfsUtil.uploadFileByStream(stream, temp.getName(), FileUtil.getFileExtensionName(temp.getName()), temp.length());
					sysFileUpload.setFastfdsLocation(res);
				} else if (saveType != null && !"".equals(saveType) && "mongodb".equals(saveType)) {// mongodb

				}
				sysFileUpload.setFILE_BUSINESS_ID(businessId);
				sysFileUpload.setFILE_BUSINESS_TABLE_NAME(businessTableName);
				sysFileUpload.setFILE_SIZE(temp.length());
				sysFileUpload.setFILE_TYPE(FileUtil.getFileExtensionName(temp.getName()));
				sysFileUpload.setATTACH_CATEGORY(category);
				sysFileUpload.setATTRIBUTE_10(uniqueId);
				// 根据uniqueId判断是否已经存入该附件
				String sql = "SELECT SA.ID FROM SYS_ATTACHMENT SA WHERE SA.ATTRIBUTE_10 = '" + uniqueId + "'";
				List<Map<String, Object>> dataList = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
				int count = 0;
				// 如果存在，则只创建关联关系，反之则
				if (dataList.size() > 0) {
					Map<String, Object> map = dataList.get(0);
					sysFileUpload = sysFileUploadService.getSysFileUploadById((String) map.get("ID"));
				} else {
					if (null == useCount) {
						sysFileUploadService.insertSysFileUpload(sysFileUpload);
					} else {
						count = Integer.parseInt(useCount);
						attachId = attachSaveId;
						if (count == 1) {
							sysFileUpload.setId(attachId);
							sysFileUploadService.insertSysFileUpload(sysFileUpload);
						}
					}
				}
				Map<String, Object> relationMap = new HashMap<String, Object>();
				relationMap.put("ARCHIVE_TABLE_ID", tableId);
				relationMap.put("RECORD_ID", businessId);
				relationMap.put("ATTACHMENT_ID", attachId);
				relationMap.put("ATTACHMENT_COVER_TYPE", "0");
				relationMap.put("UPLOAD_TYPE", uploadType);
				relationMap.put("SECRET_LEVEL", secretLevel);
				if (param.containsKey("attribute03")) {
					relationMap.put("attribute03", param.get("attribute03"));
				} else if (param.containsKey("attribute04")) {
					relationMap.put("attribute04", param.get("attribute04"));
				} else if (param.containsKey("attribute05")) {
					relationMap.put("attribute05", param.get("attribute05"));
				}
				this.insertDocRelationDataByIntfs(orgId, deptId, sysId, relationMap);

				// 如果该附件不存在，则创建mongodb数据和创建缩略图数据
				if ((dataList.size() < 1 && null == useCount) || (dataList.size() < 1 && count == 1)) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("userId", userId);
					params.put("orgId", orgId);
					params.put("deptId", deptId);
					if (null != swfUploadEvent) {
						if (saveType != null && !"".equals(saveType) && "database".equals(saveType)) {// database
							swfUploadEvent.afterSaveFileByDB(sysFileUpload, params);
						} else if (saveType != null && !"".equals(saveType) && "disk".equals(saveType)) {// disk
							swfUploadEvent.afterSaveFileByDisk(sysFileUpload, params);
						} else if (saveType != null && !"".equals(saveType) && "fastdfs".equals(saveType)) {// fastdfs
							swfUploadEvent.afterSaveFileByFastdfs(sysFileUpload, params);
						} else if (saveType != null && !"".equals(saveType) && "mongodb".equals(saveType)) {// mongodb
							swfUploadEvent.afterSaveFileByOther(sysFileUpload, stream, mongoId, secretLevel, params);
						} else {
							swfUploadEvent.afterSaveFileByOther(sysFileUpload, stream, mongoId, secretLevel, params);
						}
					}

					Map<String, Object> sysMarkerMap = new HashMap<String, Object>();
					sysMarkerMap.put("attachType", FileUtil.getFileExtensionName(temp.getName()));
					sysMarkerMap.put("attachName", temp.getName());
					sysMarkerMap.put("attachId", attachId);
					sysMarkerMap.put("loginUserId", userId);
					sysMarkerMap.put("loginIp", loginIp);
					sysMarkerMap.put("tableId", tableId);
					sysMarkerMap.put("nodeId", nodeId);
					sysMarkerMap.put("recordId", businessId);
					String path = JProperties.getFileProperties("archiveMarkerPath");
					sysMarkerMap.put("path", path);
					this.saveSysMarker(orgId, deptId, sysId, sysMarkerMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		} finally {
			try {
				if (null != os) {
					os.close();
				}
				if (null != is) {
					is.close();
				}
				if (null != out) {
					out.close();
				}
				if (null != stream) {
					stream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取条目所属附件类型的数量,并赋值
	 * @param list
	 * @throws Exception void
	 * @throws
	 */
	public void getAttachClassification(List<Map<String, Object>> list) throws Exception {
		if (list.size() > 0) {
			StringBuffer sbSql = new StringBuffer();
			sbSql.append("SELECT SA.ID, CDR.RECORD_ID PARENT_REGISTER_ID, CDR.ATTRIBUTE_01 FROM CBB_DOC_RELATION CDR\n");
			sbSql.append("LEFT JOIN SYS_ATTACHMENT SA ON SA.ID = CDR.ATTACHMENT_ID\n");
			sbSql.append("WHERE CDR.RECORD_ID IN (");
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				String rcdId = "";
				if (map.containsKey("LANTOP_FJ_RCD_ID")) {
					rcdId = "LANTOP_FJ_RCD_ID";
				} else {
					rcdId = "ID";
				}
				sbSql.append("'" + map.get(rcdId) + "'");
				if (i != list.size() - 1) {
					sbSql.append(",");
				}
			}
			sbSql.append(") AND CDR.IF_DELETE = 'N'");

			// 获取附件配置文件类型名称
			String attachmentClassName = commTableSysFieldLoader.getAttachmentClassName();// 资源文件中的类型名称
			attachmentClassName = new String(attachmentClassName.getBytes("ISO-8859-1"), "UTF-8");
			List<String> attachmentClass = new ArrayList<String>();
			if (null != attachmentClassName && !"".equals(attachmentClassName)) {
				String[] attachArray = attachmentClassName.split(";");
				for (int i = 0; i < attachArray.length; i++) {
					attachmentClass.add(attachArray[i]);
				}
			}

			List<Map<String, Object>> attachRelation = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
			for (int i = 0; i < list.size(); i++) {
				int dZCount = 0;
				int pTCount = 0;
				int hTCount = 0;
				Map<String, Object> map = list.get(i);
				String mapKey = "";
				if (map.containsKey("LANTOP_FJ_RCD_ID")) {
					mapKey = "LANTOP_FJ_RCD_ID";
				} else {
					mapKey = "ID";
				}
				String recordId = (String) map.get(mapKey);
				for (int j = 0; j < attachRelation.size(); j++) {
					Map<String, Object> arMap = attachRelation.get(j);
					String prId = (String) arMap.get("PARENT_REGISTER_ID");
					String uploadType = (String) arMap.get("ATTRIBUTE_01");
					if (recordId.equals(prId)) {
						if ("1".equals(uploadType)) {
							dZCount++;
						} else if ("2".equals(uploadType)) {
							pTCount++;
						} else if ("3".equals(uploadType)) {
							hTCount++;
						}
					}
				}
				for (int j = 0; j < attachmentClass.size(); j++) {
					String[] attachString = attachmentClass.get(j).split(",");
					if ("DZ_COUNT".equals(attachString[0])) {
						map.put(attachString[0], dZCount);
					} else if ("PT_COUNT".equals(attachString[0])) {
						map.put(attachString[0], pTCount);
					} else if ("HT_COUNT".equals(attachString[0])) {
						map.put(attachString[0], hTCount);
					}
				}
			}
		}
	}

	/**
	 * 获取条目所属附件类型的数量,返回map
	 * @param list
	 * @throws Exception void
	 * @throws
	 */
	public Map<String, Map<String, Object>> getAttachClassificationForMap(List<String> list) throws Exception {
		Map<String, Map<String, Object>> attachmentMap = new HashMap<String, Map<String, Object>>();
		if (list.size() > 0) {
			StringBuffer sbSql = new StringBuffer();
			sbSql.append("SELECT SA.ID, CDR.RECORD_ID PARENT_REGISTER_ID, CDR.ATTRIBUTE_01 FROM CBB_DOC_RELATION CDR\n");
			sbSql.append("LEFT JOIN SYS_ATTACHMENT SA ON SA.ID = CDR.ATTACHMENT_ID\n");
			sbSql.append("WHERE CDR.RECORD_ID IN (");
			for (int i = 0; i < list.size(); i++) {
				String recordId = list.get(i);
				sbSql.append("'" + recordId + "'");
				if (i != list.size() - 1) {
					sbSql.append(",");
				}
			}
			sbSql.append(") AND CDR.IF_DELETE = 'N'");

			// 获取附件配置文件类型名称
			String attachmentClassName = commTableSysFieldLoader.getAttachmentClassName();// 资源文件中的类型名称
			attachmentClassName = new String(attachmentClassName.getBytes("ISO-8859-1"), "UTF-8");
			List<String> attachmentClass = new ArrayList<String>();
			if (null != attachmentClassName && !"".equals(attachmentClassName)) {
				String[] attachArray = attachmentClassName.split(";");
				for (int i = 0; i < attachArray.length; i++) {
					attachmentClass.add(attachArray[i]);
				}
			}
			List<Map<String, Object>> attachRelation = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
			for (int i = 0; i < list.size(); i++) {
				int dZCount = 0;
				int pTCount = 0;
				int hTCount = 0;
				String recordId = list.get(i);
				for (int j = 0; j < attachRelation.size(); j++) {
					Map<String, Object> arMap = attachRelation.get(j);
					String prId = (String) arMap.get("PARENT_REGISTER_ID");
					String uploadType = (String) arMap.get("ATTRIBUTE_01");
					if (recordId.equals(prId)) {
						if ("1".equals(uploadType)) {
							dZCount++;
						} else if ("2".equals(uploadType)) {
							pTCount++;
						} else if ("3".equals(uploadType)) {
							hTCount++;
						}
					}
				}
				Map<String, Object> map = new HashMap<String, Object>();
				for (int j = 0; j < attachmentClass.size(); j++) {
					String[] attachString = attachmentClass.get(j).split(",");
					if ("DZ_COUNT".equals(attachString[0])) {
						map.put(attachString[0], dZCount);
					} else if ("PT_COUNT".equals(attachString[0])) {
						map.put(attachString[0], pTCount);
					} else if ("HT_COUNT".equals(attachString[0])) {
						map.put(attachString[0], hTCount);
					}
				}
				attachmentMap.put(recordId, map);
			}
		}
		return attachmentMap;
	}

	/**
	 * 获取文件加密KEY，返回Sting类型KEY
	 * @param file
	 * @return key
	 * @throws Exception String
	 * @throws
	 */
	public String getFileKeyByMd5(File file) throws Exception {
		String key = "";
		String strFile = "";
		String info = "";
		try {
			// 获取文件属性
			info = geFileInfo(file);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			// 对文件进行加密
			strFile = EnFileCode(file.getPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 加密文件属性信息
		String str = EnStringCode(info);
		// 返回加密后的key
		key = EnStringCode(str + strFile);
		return key;
	}

	/**
	 * 获取文件属性值信息
	 * @throws IOException
	 * @文件属性:获取文件属性值信息
	 * @return  String
	 * @throws
	 */
	private String geFileInfo(File srcFile) throws IOException {
		// 获取文件路径
		String path = srcFile.getPath();
		// 获取文件名称
		String fileTitle = srcFile.getName();
		// 文件长度
		String fLength = String.valueOf(srcFile.length());
		// 文件创建时间
		String startTime = Files.readAttributes(Paths.get(path), BasicFileAttributes.class).creationTime().toString();
		// 最后修改时间
		String lastDate = String.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(srcFile.lastModified()));
		// 是否可读
		boolean read = srcFile.canRead();
		// 是否可写
		boolean write = srcFile.canWrite();
		// 是否被隐藏
		boolean hide = srcFile.isHidden();
		// 获取文件后缀名
		String fn = fileTitle.substring(fileTitle.lastIndexOf("."), fileTitle.length());
		// String info="文件路径:"+path;
		// 字符串格式如:fileName:122.doc \n
		String info = "fileName:" + fileTitle + "\nstartTime:" + startTime + "\npath:" + path + "\nupdteTime:" + lastDate + "\nfileSmall:" + fLength + "\nfileSuffix:" + fn + "\nsfRead:" + read + "\nsfwrite:" + write + "\nsfHide:" + hide;
		System.out.println(info);
		return info;
	}

	/**
	 * 字符串的md5加密
	 */
	private String EnStringCode(String str) {
		try {
			// 拿到一个MD5转换器(如果想要SHA1加密参数换成"SHA1"）
			MessageDigest messageDigest = MessageDigest.getInstance("md5");
			// 输入的字符串转换成字节数组
			byte[] inputByteArray = str.getBytes();
			// inputByteArray是输入字符串转换得到的字符串
			messageDigest.update(inputByteArray);
			// 转换并返回结果，也是字节数组，包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 字符数组转换成字符串返回
			return byteArrayToHex(resultByteArray);
		} catch (NoSuchAlgorithmException e) {
			return null;
		}

	}

	/**
	 * 返回需要格式字符串
	 */
	private String byteArrayToHex(byte[] byteArray) {
		// 初始化一个字符数组,用来存放每个16进制字符
		char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
		// new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符）
		char[] resultCharArry = new char[byteArray.length * 2];
		// 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArry[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArry[index++] = hexDigits[b & 0xf];
		}
		// 返回数组组合成字符返回
		return new String(resultCharArry);
	}

	/**
	 * 文件的md5加密
	 * @param inFile
	 * @return
	 * @throws IOException String
	 * @throws
	 */
	private String EnFileCode(String inFile) throws IOException {

		// 缓冲区大小(这个可以抽出一个参数)
		int bufferSize = 256 * 1024;
		FileInputStream fileInputStream = null;
		DigestInputStream digestInputStream = null;
		try {
			// 拿到一个MD5转换器(同样，这里可以转化成SHA1)
			MessageDigest messageDigest = MessageDigest.getInstance("md5");
			fileInputStream = new FileInputStream(inFile);
			digestInputStream = new DigestInputStream(fileInputStream, messageDigest);
			// read的过程中进行MD5处理,直到读完文件
			byte[] buffer = new byte[bufferSize];
			while (digestInputStream.read(buffer) > 0)
				;
			// 获取最终的MessageDigest
			messageDigest = digestInputStream.getMessageDigest();
			// 拿到结果,也是字节数组，包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 同样，把字节数组转换成字符串
			return byteArrayToHex(resultByteArray);
		} catch (NoSuchAlgorithmException e) {
			return null;
		} finally {
			try {
				digestInputStream.close();
			} catch (Exception e) {

			}
			try {
				fileInputStream.close();
			} catch (Exception e) {

			}
		}
	}

	/**
	 * 获取流文件
	 * @param mongoId
	 * @param fileId
	 * @param sysId
	 * @return
	 * @throws Exception InputStream
	 * @throws
	 */
	public InputStream getAttachmentIs(String mongoId, String fileId, String sysId) throws Exception {
		SysFileUpload sfu = sysFileUploadService.getSysFileUploadById(fileId);
		String fileName = sfu.getFILE_NAME();
		String lastName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		String docType = "";
		if (JProperties.getFileProperties("audioformat").toLowerCase().indexOf(lastName.toLowerCase()) != -1) {
			docType = "flv";
		} else if (JProperties.getFileProperties("videoformat").toLowerCase().indexOf(lastName.toLowerCase()) != -1) {
			docType = "flv";
		} else if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(lastName.toLowerCase()) != -1) { // 文档
			docType = "pdf";
		}
		if ("gd".equals(lastName.toLowerCase())) {
			docType = "";
		}
		InputStream in = null;
		// 如果是PDF格式的才进行传递流
		if ("pdf".equals(docType)) {
			try {
				// 获取存储方式
				String saveType = JProperties.getFileProperties("savetype");
				if (saveType != null && !"".equals(saveType) && "database".equals(saveType)) { // 数据库
					in = docService.getFileByDatabase(fileId);
				} else if (saveType != null && !"".equals(saveType) && "disk".equals(saveType)) { // 磁盘
					in = docService.getFileByDisk(fileId);
				} else if (saveType != null && !"".equals(saveType) && "fastdfs".equals(saveType)) { // fastdfs
					in = new ByteArrayInputStream(docService.getFileByFastdfs(fileId));
				} else if (saveType != null && !"".equals(saveType) && "mongodb".equals(saveType)) { // mongodb
					in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(fileId + docType);
				} else if (saveType != null && !"".equals(saveType) && "s3".equals(saveType)) { // mongodb
					in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(fileId + docType);
				} else {
					in = mongoDBManager.getMongoDBController(sysId).getGridFSIOById(fileId + docType);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return in;
	}

	/**
	 * 删除源转换后文件，插入电子签名后的电子文件
	 * @param param
	 * @throws Exception void
	 * @throws
	 */
	public void insertMongodbByInputStream(Map<String, Object> param, InputStream is) throws Exception {
		String mongoId = (String) param.get("mongoId");
		String attachId = (String) param.get("attachId");
		String attachName = (String) param.get("attachName");
		String secretLevel = (String) param.get("secretLevel");
		Map<String, String> map = new HashMap<String, String>();
		String keyfiled = mongoDBManager.getMongoDBController(mongoId).getKeyfiled();
		map.put(keyfiled, attachId);
		map.put("secret_level", secretLevel);
		mongoDBManager.getMongoDBController(mongoId).deleteGridFS(attachId);
		mongoDBManager.getMongoDBController(mongoId).insertGridFS(is, attachName, map);
	}

	/**
	 * 更新附件信息
	 * @throws Exception void
	 * @throws
	 */
	public void updateAttachmentData(Map<String, Object> param) throws Exception {
		String id = (String) param.get("attachId");
		String contractid = (String) param.get("contractid");
		SysFileUpload sysFileUpload = this.hibernateDao.get(SysFileUpload.class, id);
		sysFileUpload.setATTRIBUTE_07(contractid);
		this.hibernateDao.save(sysFileUpload);
	}

	public Map<String, Object> getAttachmentDataById(String attachId) throws Exception {
		String sql = "SELECT ID,ATTACH_NAME,PARENT_TABLE_ID,PARENT_REGISTER_ID,ATTACH_TYPE,ATTACH_SIZE,LAST_UPDATE_DATE,LAST_UPDATED_BY,LAST_UPDATE_IP,CREATION_DATE,CREATED_BY,VERSION,ATTRIBUTE_01,ATTRIBUTE_02,ATTRIBUTE_03,ATTRIBUTE_04,ATTRIBUTE_05,ATTRIBUTE_06,ATTRIBUTE_07,ATTRIBUTE_08,ATTRIBUTE_09,ATTRIBUTE_10,UPLOAD_PATH,PARENT_TABLE_FIELD,ATTACH_CATEGORY,SECRET_LEVEL,FASTDFS_LOCATION from sys_attachment sa where sa.id = '"
				+ attachId + "' ORDER BY CREATION_DATE, ATTACH_NAME ASC";
		List<Map<String, Object>> attachs = this.jdbcAvicit.getJdbcTemplate().queryForList(sql);
		if (attachs.size() > 0) {
			return attachs.get(0);
		}
		return null;
	}

	/**
	 * 根据附件id和条目id删除relation数据
	 * @param recordId
	 * @param attachId
	 * @throws Exception void
	 * @throws
	 */
	public void deleteCbbDocRelationByRecordIAttachId(String recordId, String attachId) throws Exception {
		// 删除全文文件关系
		String delRelation = "DELETE FROM CBB_DOC_RELATION WHERE ATTACHMENT_ID = '" + attachId + "' AND RECORD_ID = '" + recordId + "'";
		jdbcAvicit.getJdbcTemplate().execute(delRelation);
	}
}
